<template>
  <div class="app-container">
    <div
      v-show="
        !supplierInfo.visiable && !supplierProduct.visible && !orgInfos.visible
      "
    >
      <!-- 条件栏 -->
      <NewPageFilter
        v-model:query="filterInfo.query.queryMap"
        :query-more-json="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :clear-type="clearType"
        :slip-select-request="slipSelectRequest"
      >
      </NewPageFilter>
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-uploadFile>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :checkBox="false"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
      >
        <template v-slot:col-supplierName="scope">
          <span
            v-if="$permission('supplier:list')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.supplierName }}</span
          >
          <span v-else>{{ scope.row.supplierName }}</span>
        </template>
      </table-container>
    </div>
    <!-- 添加供应商 -->
    <suppllier-add
      v-if="supplierInfo.visiable"
      v-model:visible="supplierInfo.visiable"
      v-model:title="supplierInfo.title"
      @returnModify="search"
    />
    <SupplierProduct
      v-if="supplierProduct.visible"
      v-model:visible="supplierProduct.visible"
      :table-row="supplierProduct.data"
      @returnBack="getList"
      @callback="getList"
    />
    <orgDetails
      v-if="orgInfos.visible"
      v-model:visible="orgInfos.visible"
      :id="orgInfos.id"
      @returnBack="getList"
    />
    <defaultSetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    >
    </defaultSetPreference>
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="supplier">
import { getsupplierscustomizeListPages, deleteSupplier } from '@/api/core.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import SuppllierAdd from './detail/index'
import SupplierProduct from './supplierProduct'
import orgDetails from './detail/orgDetails'
import { exportTemplateExcel } from '@/api/pub'
import defaultSetPreference from '@/components/SetPreference/defaultSetPreference'
import { ElLoading } from 'element-plus'
const { proxy } = getCurrentInstance()
const uploadInfo = ref({
  action:
    import.meta.env.VITE_APP_BASE_API + '/core/supplierProducts/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const slipSelectRequest = ref(true)
const clearType = ref(true)
// 过滤相关配置
const filterInfo = ref({
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
    queryParams: {
      searchType: 'org',
      searchField: 'supplierId',
      sort: 'create_time desc,id asc',
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('supplier:add'),
      event: add,
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
    },
    { type: 'slot', value: 'uploadFile' },
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: search,
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '140',
    btList: [
      {
        label: '关联产品',
        event: openSupplierProduct,
        show: proxy.$permission('supplier:product'),
      },
      {
        label: '解除关系',
        event: disengagement,
        show: proxy.$permission('supplier:relieve'),
      },
      // TODO: 2020.5.22 解除关系功能暂时不上
    ],
  },
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '名称', value: 'name', type: 'input', required: true },
    { label: '编码', value: 'code', type: 'input', required: true },
  ],
  rules: {},
  labelWidth: '100px',
})
const supplierInfo = ref({
  visiable: false,
  title: '新增供应商',
})
const supplierProduct = ref({
  visible: false,
})
const orgInfos = ref({
  visible: false,
  id: '',
})
watch(
  () => proxy.$route,
  (route) => {
    const params = route.params
    if (params && params.supplierId) {
      openDetails(params.supplierId)
    }
  },
  {
    immediate: true,
  }
)
let obj = ref({
  supplierName: {
    label: '供应商名称',
    value: 'supplierName',
    componentType: 'input',
    show: false,
    hidden: true,
    type: 'slot',
  },

  serviceScopeValue: {
    label: '服务范围',
    value: 'serviceScopeValue',
    asValue: 'serviceScope',
    componentType: 'select-model',
    code: 'service_scope',
    show: false,
    hidden: true,
  },
})
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
  orgStatusValue: {
    label: '供应商状态',
    value: 'orgStatusValue',
    asValue: 'orgStatus',
    componentType: 'select-model',
    code: 'new_enabled_type',
    show: false,
    hidden: true,
  },
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
onMounted(() => {
  getCustomize()
  // getList();
})
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey: 'coreSupplierKey-com.slip.spd.entity.vo.core.CoreSupplierVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      proxy.$nextTick(() => {
        let data = res.data
        filterInfo.value.query.customizeUserVO = data
        tableInfo.value.fieldList = proxy.$fn.setFieldList(
          tableInfo.value.fieldList,
          data.detail
        )
        let searchInfo = proxy.$fn.setSearchList(
          filterInfo.value.searchList,
          data.detail
        )
        filterInfo.value.query.queryMap = {
          ...searchInfo.queryMap,
        }

        filterInfo.value.searchList = searchInfo.searchList
        filterInfo.value.searchList.forEach((item) => {
          item.event = search
        })
        filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
          filterInfo.value.query.queryMap
        )
        slipSelectRequest.value = _slipSelectRequest
        tableInfo.value.api = getsupplierscustomizeListPages
        getList()
      })
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function setPreferenceCallback(obj) {
  let vo = proxy.$fn.deepClone(obj.customizeUserVO)
  updateUserCustomize(vo).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}

function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  advancedSearchInfo.value.data = obj.data
  proxy.$nextTick(() => {
    getList()
  })
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}

function search() {
  advancedSearchInfo.value.data = {}
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}

function openDetails(id) {
  orgInfos.value.id = id
  orgInfos.value.visible = true
}

// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 添加
function add() {
  supplierInfo.value.visiable = true
}
// 解除关系
function disengagement(data) {
  let ids = [data.id]
  proxy
    .$confirm(
      `解除关系将清空与【${data.supplierName}】绑定的所有产品，确认解除关系吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      deleteSupplier(ids).then((resp) => {
        if (resp && resp.success) {
          tableInfo.value.initCurpage = Math.random()
          tableInfo.value.refresh = Math.random()
        }
      })
    })
}
//打开供应商产品界面
function openSupplierProduct(row) {
  sessionStorage.setItem('storeRowId', row.id)
  supplierProduct.value.visible = true
  supplierProduct.value.data = { ...row }
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  orgInfos.value.id = row.supplierId
  orgInfos.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function downloadTemplate() {
  exportTemplateExcel('supplier_product').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function beforeUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function uploadSuccess(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
